<template>
  <div class="sales-report">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>销售报告</h2>
          <el-select v-model="timeFilter" placeholder="选择时间范围" clearable style="width: 120px; background: var(--primary-light); border-color: var(--primary-color); color: var(--primary-color); border-radius: 4px;">
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
          </el-select>
          <el-button type="primary" style="margin-left: 16px;" @click="handleExportReport">导出报告</el-button>
        </div>
      </template>

      <el-empty v-if="loading" description="加载中...">
        <el-icon class="is-loading"><Loading /></el-icon>
      </el-empty>

      <el-empty v-else-if="filteredOrders.length === 0" description="暂无订单数据" />

      <template v-else>
        <el-table
          v-loading="loading"
          :data="paginatedOrders"
          style="width: 100%"
        >
          <el-table-column prop="order_number" label="订单编号" width="180" />
          <el-table-column prop="payment_time" label="下单时间" width="180">
            <template #default="{ row }">
              {{ row.payment_time ? new Date(row.payment_time).toLocaleString() : '未付款' }}
            </template>
          </el-table-column>
          <el-table-column prop="total_amount" label="订单金额" width="120">
            <template #default="{ row }">
              ¥{{ parseFloat(row.total_amount).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'cancelled'"
                type="danger"
                size="small"
                @click="handleDeleteOrder(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="商品信息" min-width="200">
            <template #default="{ row }">
              <div v-for="item in row.items" :key="item.id" class="order-item">
                <span>{{ item.product_name || item.product?.name || '未知商品' }}</span>
                <span class="item-quantity">x{{ item.quantity }}</span>
                <span class="item-price">¥{{ parseFloat(item.unit_price || item.price || 0).toFixed(2) }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalOrders"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Loading } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

const loading = ref(false)
const timeFilter = ref('week')
const currentPage = ref(1)
const pageSize = ref(10)

// 销售数据
const salesData = ref({
  total_sales: 0,
  order_count: 0,
  product_sales: [],
  category_sales: [],
  daily_sales: []
})

// 订单列表数据
const orders = ref([])
const allOrders = ref([]) // 存储所有订单，用于前端筛选
const total = ref(0)

// 生成日期序列
const generateDateRange = (period) => {
  const dates = []
  const today = new Date()
  let startDate
  
  if (period === '7days') {
    // 最近7天（含今天）
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      dates.push(date.toISOString().split('T')[0])
    }
  } else if (period === '30days') {
    // 最近30天（含今天）
    for (let i = 29; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      dates.push(date.toISOString().split('T')[0])
    }
  }
  
  return dates
}

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      loading.value = false
      return
    }

    // 获取所有订单数据
    console.log('fetchOrders: 开始获取所有订单数据...')
    const response = await axios({
      method: 'get',
      url: '/api/sales-orders/',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    console.log('获取订单列表响应:', response.data)

    // 从响应中获取订单数据
    let ordersData = []
    if (response.data && response.data.data && Array.isArray(response.data.data.items)) {
      ordersData = response.data.data.items
      total.value = response.data.data.total || ordersData.length
    } else if (Array.isArray(response.data)) {
      ordersData = response.data
      total.value = ordersData.length
    }
    
    allOrders.value = ordersData
    console.log('fetchOrders: 解析后的订单数组长度:', allOrders.value.length)

    if (allOrders.value.length > 0) {
      // 1. 定义目标订单状态
      const targetStates = ['paid', 'shipped', 'completed']

      // 2. 生成当前选择时间范围的日期序列
      const datesInRange = generateDateRange(timeFilter.value)
      console.log('fetchOrders: 生成的日期序列:', datesInRange)

      // 3. 初始化每日销售数据统计对象
      const dailySalesData = {}
      datesInRange.forEach(date => {
        dailySalesData[date] = { count: 0, amount: 0 }
      })

      // 4. 遍历订单，进行统计
      allOrders.value.forEach(order => {
        if (order.payment_time && targetStates.includes(order.status)) {
          const paymentDate = new Date(order.payment_time).toISOString().split('T')[0]
          
          if (dailySalesData[paymentDate]) {
            dailySalesData[paymentDate].count++
            dailySalesData[paymentDate].amount += parseFloat(order.total_amount) || 0
          }
        }
      })

      // 5. 格式化数据用于图表
      const trendData = datesInRange.map(date => ({
        date,
        orders: dailySalesData[date].count,
        amount: dailySalesData[date].amount
      }))

      // 6. 更新销售数据
      salesData.value = {
        total_sales: Object.values(dailySalesData).reduce((sum, data) => sum + data.amount, 0),
        order_count: total.value,
        daily_sales: trendData
      }

      console.log('销售数据更新:', salesData.value)
      
      // 更新筛选后的订单
      applyFilters()
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    allOrders.value = []
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 应用筛选条件
const applyFilters = () => {
  console.log('应用筛选条件，当前时间范围:', timeFilter.value)
  
  let filtered = [...allOrders.value]
  
  // 按时间范围筛选
  if (timeFilter.value) {
    const startDate = new Date()
    if (timeFilter.value === 'week') {
      startDate.setDate(startDate.getDate() - 7)
    } else if (timeFilter.value === 'month') {
      startDate.setMonth(startDate.getMonth() - 1)
    }
    
    const startDateString = startDate.toISOString().split('T')[0]
    const endDateString = new Date().toISOString().split('T')[0]
    
    console.log('筛选日期范围:', startDateString, '至', endDateString)
    
    filtered = filtered.filter(order => {
      const orderDate = new Date(order.created_at).toISOString().split('T')[0]
      return orderDate >= startDateString && orderDate <= endDateString
    })
  }
  
  console.log('筛选后的订单数量:', filtered.length)
  orders.value = filtered
  
  // 每次筛选后重置页码
  currentPage.value = 1
}

// 监听时间筛选变化
watch(timeFilter, () => {
  // 如果已经有订单数据，则直接应用筛选，否则重新获取
  if (allOrders.value.length > 0) {
    applyFilters()
  } else {
    fetchOrders()
  }
})

// 计算订单列表
const filteredOrders = computed(() => {
  // 对订单按照支付时间降序排序
  return orders.value.sort((a, b) => {
    const timeA = a.payment_time ? new Date(a.payment_time).getTime() : 0;
    const timeB = b.payment_time ? new Date(b.payment_time).getTime() : 0;
    return timeB - timeA; // 降序排序
  });
})

// 计算分页后的订单列表
const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 计算总订单数
const totalOrders = computed(() => filteredOrders.value.length)

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'info',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 添加删除订单函数
const handleDeleteOrder = async (order) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 检查订单状态
    if (order.status !== 'cancelled') {
      ElMessage.warning('只能删除已取消的订单')
      return
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.order_number} 吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用删除API
    await axios({
      method: 'delete',
      url: `/api/sales-orders/${order.id}/`,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('删除成功')
    
    // 重新获取订单列表
    await fetchOrders()
  } catch (error) {
    if (error.message === 'cancel') {
      return
    }
    console.error('删除订单失败:', error)
    let errorMsg = '删除订单失败'
    
    // 处理后端返回的具体错误信息
    if (error.response?.data?.message) {
      errorMsg = error.response.data.message
    } else if (error.response?.data?.detail) {
      errorMsg = error.response.data.detail
    }
    
    ElMessage.error(errorMsg)
  }
}

// 导出报告方法
const handleExportReport = () => {
  // 1. 获取当前筛选后的订单
  const data = filteredOrders.value.map(order => {
    // 商品明细拼接
    const items = (order.items || []).map(item => `${item.product_name || item.product?.name || '未知商品'} x${item.quantity} ¥${parseFloat(item.unit_price || item.price || 0).toFixed(2)}`).join('; ')
    return {
      '订单编号': order.order_number,
      '下单时间': order.payment_time ? new Date(order.payment_time).toLocaleString() : '未付款',
      '订单金额': order.total_amount,
      '订单状态': getStatusText(order.status),
      '商品明细': items,
      '客户名称': order.customer_name || order.user_name || '',
      '联系电话': order.phone || order.contact_phone || '',
      '配送地址': order.address || order.shipping_address || '',
      '备注': order.remark || ''
    }
  })
  if (data.length === 0) {
    ElMessage.warning('暂无可导出的订单数据')
    return
  }
  // 2. 生成 worksheet & workbook
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '销售报告')
  // 3. 下载
  XLSX.writeFile(wb, `销售报告_${new Date().toISOString().slice(0,10)}.xlsx`)
  ElMessage.success('导出成功')
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.sales-report {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
  border-bottom: 1px dashed #ebeef5;
}

.order-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.item-quantity {
  margin: 0 10px;
  color: #606266;
  font-size: 13px;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  min-width: 60px;
  text-align: right;
}

.chart-container {
  height: 400px;
}

.chart {
  height: 100%;
  width: 100%;
}

.growth-rate.positive {
  color: var(--primary-color);
}

.growth-rate.negative {
  color: var(--el-color-danger);
}
</style> 